﻿<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%> 
<%@ Assembly Name="iTextSharp, Version=4.1.6.0, Culture=neutral, PublicKeyToken=8354ae6d2174ddca"%>
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" %> 
<%@ Import Namespace="iTextSharp.text" %>
<%@ Import Namespace="iTextSharp.text.pdf" %>

<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %> 
<%@ Import Namespace="Microsoft.SharePoint" %>

<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<asp:Content ID="Content2" contentplaceholderid="PlaceHolderPageTitle" runat="server">
	<SharePoint:EncodedLiteral ID="EncodedLiteral4" runat="server" text="PDF Form Fields" EncodeMethod='HtmlEncode'/>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderId="PlaceHolderPageTitleInTitleArea" runat="server">
	<SharePoint:EncodedLiteral ID="EncodedLiteral5" runat="server" text="PDF Form Fields" EncodeMethod='HtmlEncode'/>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderId="PlaceHolderPageDescription" runat="server">
	<SharePoint:EncodedLiteral ID="EncodedLiteral6" runat="server" text="Below are all the fields found in the PDF Form that is the document template. Check the fields that you would like promoted to the Sharepoint Content Type." EncodeMethod='HtmlEncode'/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

    <br />
    <table>
    <tr><td class="ms-vb2" width="150">Document Template:</td><td  class="ms-vb2"><asp:Label ID="labelDocumentTemplateUrl" Text="No document template defined." runat="server" /></td></tr>
    <tr><td>&nbsp;</td><td><asp:Button id="promoteProperties" runat="server" OnClick="promoteProperties_Click" Text="Update" /><br /><asp:Label ID="lblMessage" Text="" runat="server" /></td></tr>
    </table>
    <br />

    <asp:Label ID="labelText" Text="" runat="server" />

    
    
</asp:Content>
<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        EnsureChildControls();

        // Get the SPContent Type
        SPWeb spWeb = SPContext.Current.Site.RootWeb;
        SPContentTypeId spContentTypeId = new SPContentTypeId(Request.QueryString["ctype"]); 
        SPContentType spContentType = spWeb.ContentTypes[spContentTypeId];
        
        // Open the document template (i.e. the PDF Form)
        String documentTemplateUrl;
        if (spContentType.DocumentTemplate.IndexOf("/") > 0)
        {
            documentTemplateUrl = spContentType.DocumentTemplate;
        }
        else
        {
            documentTemplateUrl = spContentType.DocumentTemplateUrl;
        }

        // Can only lookup information if there's a document template.
        if (documentTemplateUrl == "")
        {
            return;
        } else
        {
            labelDocumentTemplateUrl.Text = documentTemplateUrl;
        }


        // Open the Document Template (i.e. the PDF Form). Since it's in SharePoint, it's an SPFile).
        // To do this, get the SPFolder that holds the SPFile. This will require iterating down the folders.
        // Do the test by position in the URL, instead of by string testing as someone can name a subfolder with the same name as the file.
        SPFolder spFolder = null;
        int dirCurr = 0;
        int dirMax = documentTemplateUrl.Split("/".ToCharArray()).Length;
        foreach (String directory in documentTemplateUrl.Split("/".ToCharArray()))
        {
            dirCurr++;
            if (directory != "" && dirCurr < dirMax)
            {
                if (spFolder == null)
                {
                    spFolder = spWeb.Folders[directory];
                }
                else
                {
                    spFolder = spFolder.SubFolders[directory];
                }
            }
        }
        String fileName = documentTemplateUrl.Split("/".ToCharArray())[documentTemplateUrl.Split("/".ToCharArray()).Length - 1];
        SPFile spFile = spFolder.Files[fileName];
        PdfReader pdfReader = new PdfReader(spFile.OpenBinary(), null);

        // Output all the fields in the PDF form.
        // If any match fields for the SPContentType, then select the Checkbox

        ContentPlaceHolder cp = (ContentPlaceHolder)Master.FindControl("PlaceHolderMain");

        System.Web.UI.WebControls.Table table = new System.Web.UI.WebControls.Table();
        TableHeaderRow tableHeaderRow = new TableHeaderRow();
        table.BorderWidth = 1;
        
        TableHeaderCell tableHeaderCell = new TableHeaderCell();
        tableHeaderCell.Text = "PDF Form Field Name";
        tableHeaderCell.CssClass = "ms-vb2";
        tableHeaderCell.Attributes["width"] = "150";
        tableHeaderRow.Cells.Add(tableHeaderCell);

        tableHeaderCell = new TableHeaderCell();
        tableHeaderCell.Text = "Promote";
        tableHeaderCell.CssClass = "ms-vb2";
        tableHeaderRow.Cells.Add(tableHeaderCell);
        
        table.Rows.Add(tableHeaderRow);

        foreach (System.Collections.DictionaryEntry pdfField in pdfReader.AcroFields.Fields)
        {
            TableRow tableRow = new TableRow();
            TableCell tableCell = new TableCell();
            tableRow.Cells.Add(tableCell);
            tableCell.Text = pdfField.Key.ToString();
            tableCell.CssClass = "ms-vb2";

            tableCell = new TableCell();
            tableCell.CssClass = "ms-vb2";
            tableCell.Attributes["align"] = "center";
            tableRow.Cells.Add(tableCell);
            String checkedValue = "";
            if (spContentType.Fields.ContainsField("pdf_" + pdfField.Key)) {checkedValue = "CHECKED";}
            tableCell.Text = "<input name='pdf_" + pdfField.Key + "' " + checkedValue + " type='checkbox'>";
            table.Rows.Add(tableRow);
        }

        cp.Controls.Add(table);
        
    }
    
    //TODO:
    public void promoteProperties_Click(Object s, EventArgs e)
    {
        // Open the SPContentType and iterate through all PDF fields
        SPWeb spWeb = SPContext.Current.Site.RootWeb;
        SPContentTypeId spContentTypeId = new SPContentTypeId(Request.QueryString["ctype"]);
        SPContentType spContentType = spWeb.ContentTypes[spContentTypeId];

        // For each "pdf_" field, find a corresponding one in the fields that were just sent back with checkboxes.
        int fieldsToDelete = 0;
        foreach (SPField spField in spContentType.Fields)
        {
            // If the field isn't found in the checkboxes being returned, then delete the SPField from the SPContentType.Fields
            if (spField.Title.Substring(0,4) == "pdf_" && Request[spField.Title] == null)
            {
                spContentType.FieldLinks.Delete(spField.Title);
                fieldsToDelete++;
            }
            if (fieldsToDelete > 0)
            {
                spContentType.Update();
            }

        }

        // For each checkbox returned, find a corresponding field in the SPContentType.Fields
        // If a field isn't found, then add a new SPField in SPContentType.Fields. The field name will be "pdf_" + the PDF Form's field name.
        int fieldsToAdd = 0;
        foreach (String formVariable in Request.Form ) 
        {
            if (formVariable.Substring(0, 4) == "pdf_")
            {
                if (Request.Form[formVariable].ToLower() == "on")
                {
                    if (!spContentType.Fields.ContainsField(formVariable))
                    {
                        fieldsToAdd++;
                        // If Site Column does not exist, then create.
                        if (!spWeb.Fields.ContainsField(formVariable))
                        {
                            SPField spField;
                            spField = spWeb.Fields.CreateNewField(SPFieldType.Text.ToString(), formVariable);
                            spField.Group = "PDF Forms";
                            spField.Required = false;
                            spField.ShowInDisplayForm = false;
                            spField.ShowInEditForm = false;
                            spWeb.Fields.Add(spField);
                            spWeb.Update();
                        }
                        
                        SPFieldLink spFieldLink = new SPFieldLink(spWeb.Fields[formVariable]);
                        spContentType.FieldLinks.Add(spFieldLink);
                        spContentType.Update();
                    }
                }
            }
        }
 
        Response.Redirect("PdfForm.aspx?ctype=" + Request.QueryString["ctype"] + "&fieldsToDelete=" + fieldsToDelete.ToString() + "&fieldsToAdd=" + fieldsToAdd.ToString());
    }
    
</script>